package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService{
    @Autowired
    private StrategyCommentRepository repository; //crud


    @Autowired
    private MongoTemplate template; //高级查询

    @Override
    public void save(StrategyComment comment) {
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //mongodb分页操作
        //只能通过查询他的高查结果，自己封装成page对象
        Query query = new Query();  //分页条件

        //查询条件
        if(qo.getDetailId()!=-1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //查询总数  根据这个类来找到文档查询总数
        Long total = template.count(query, StrategyComment.class);
        if(total==0){
            Page.empty();  //如果total为null，返回一个空
        }
        //分页条件 根据创建时间倒序分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");
        //拼接查询条件
        query.with(pageable);
        //查询所有结果
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list,pageable,total);  //实现分页方法
    }

    @Override  //点赞操作
    public void commentThumbUp(String toid, Long userId) {
        //判断当前请求是点赞还是取消
        Optional<StrategyComment> op = repository.findById(toid);
        StrategyComment comment = op.get();
        if(comment==null){
            return;
        }
        List<Long> thumbuplist = comment.getThumbuplist();
        if(!thumbuplist.contains(userId)){
            //点赞操作，点赞+1，用户id加到点赞列表
            comment.setThumbupnum(comment.getThumbupnum()+1);
            thumbuplist.add(userId);
        }else {
            //取消操作
            comment.setThumbupnum(comment.getThumbupnum()-1);
            thumbuplist.remove(userId);
        }
        repository.save(comment);//修改数据，没id为增加，有为修改
    }
}
